package com.gouda.temporary;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author songjunjie
 */
public class StringToDateConverter implements Converter<String, Date> {
    private String dateFormatString = null;
    private static String[] pattern = new String[]{"yyyy-MM", "yyyyMM", "yyyy/MM",
            "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMddHHmmss",
            "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"};

    public void setDateFormat(String dateFormat) {
        this.dateFormatString = dateFormat;
    }

    public Date convert(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        try {
            if (StringUtils.isNotEmpty(dateFormatString)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
                return dateFormat.parse(source);
            } else {
                Date date = DateUtils.parseDate(source, pattern);
                return date;
            }
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期转换失败:"+source,e);
        }
    }
}
